<template>
  
  <div class="Register-container">
    <el-form ref="ruleFormRef" style="max-width: 100%;margin-left: 10%;" :model="ruleForm" status-icon :rules="rules"
      label-width="auto" class="demo-ruleForm">
      <el-form-item label="请输入手机号" prop="phone">
        <el-input style="width: 250px;" v-model="ruleForm.phone" @keyup.enter="submitForm(ruleFormRef)" />
      </el-form-item>

      <el-form-item label="请输入验证码" prop="captcha">
        <el-input style="width: 100px;" v-model="ruleForm.captcha" @keyup.enter="submitForm(ruleFormRef)" />
        <el-button style="margin-left: 10px;" type="primary" @click="getCaptcha">获取验证码</el-button>
      </el-form-item>

      <el-form-item>
        <el-button style="margin-left: 15%;margin-top: 10px;" type="success" @click="submitForm(ruleFormRef)">
          注册
        </el-button>
        <el-button style="margin-left: 30px;margin-top: 10px;" @click="router.push('/')">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
  
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus';
import { registerApi, getCodeApi } from '@/api/api';
import router from '@/router';


// 格式化时间的方法  去掉T
const formatTime = (time: string) => {
  if (!time) return '';
  return time.replace('T', ' ');
}


//声明表单对象名称，关联整个表单中的元素
const ruleFormRef = ref<FormInstance>()
//手机号校验
const checkPhone = (rules: any, value: any, callback: any) => {
  rules
  if (!value) {
    return callback(new Error('手机号不能为空'))
  }
  callback()
}
//密码校验
const checkcaptcha = (rules: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('验证码不能为空'))
  }
  else if (!/^\d{6}$/.test(value)) {
    return callback(new Error('验证码为6位数字'))
  }
  callback(); // 校验通过
}

// 表单的数据
const ruleForm = reactive({
  phone: '',
  captcha: '',
})
//校验规则数组
const rules = reactive<FormRules<typeof ruleForm>>({
  captcha: [{ validator: checkcaptcha, trigger: 'blur' }],
  phone: [{ validator: checkPhone, trigger: 'blur' }],
})

//获取验证码
const getCaptcha = async () => {
  //发送验证码请求
  const response = await getCodeApi({ phone: ruleForm.phone });
  console.log('验证码响应数据', response);
  if (response.code === 200) {
    ElMessage.success('验证码发送成功，请注意查收,10分钟内有效');
  } else {
    ElMessage.error(response.msg);
  }
}


// axios请求需要通过异步方式声明：async/await
async function handleRegister() {
  try {
    const response = await registerApi({ phone: ruleForm.phone, pwd: ruleForm.captcha });
    console.log('注册响应数据', response);
    if (response.code !== 200) {
      ElMessageBox.confirm(
        '注册成功! 请返回登录页面进行登录,初始密码为手机号后6位',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success',
        }
      ).then(async () => {
        router.push('/')
        //清空表单数据
        ruleForm.phone = '';
        ruleForm.captcha = '';
      }).catch(() => {
        ElMessage.info('已取消');
      });


    } else {
      ElMessage.error('注册失败，请检查手机号或者验证码是否正确');
    }
  } catch (error) {
    ElMessage.error('操作失败，请稍后再试');
  }
}

//提交数据
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      //如果验证通过，这调用注册方法
      handleRegister()
    } else {
      ElMessage({
        message: '数据格式有误',
        type: 'error',
        duration: 1000, // 消息提示框显示的时间，单位是毫秒
      });
    }
  })
}


</script>

<style scoped>
.Register-container {
  /* background-image: src('@/assets/3.jpg'); */
  border-radius: 10px;
  padding-top: 80px;
  padding-bottom: 30px;
  background-color: aqua;
  margin: 30px auto;
  width: 500px
}
</style>